package com.srcbox.file.util

import android.R
import android.app.Activity
import android.app.ActivityManager
import android.content.*
import android.content.pm.ResolveInfo
import android.content.res.ColorStateList
import android.content.res.Resources
import android.database.Cursor
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.text.TextUtils.SimpleStringSplitter
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.accessibility.AccessibilityManager
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SwitchCompat
import androidx.core.content.FileProvider
import androidx.core.graphics.drawable.DrawableCompat
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.srcbox.file.data.AppSetting
import java.io.*
import java.lang.reflect.Field
import java.lang.reflect.Method


object EggUtil {


    private val MIME_MapTable =
        arrayOf(
            arrayOf(".3gp", "video/3gpp"),
            arrayOf(".apk", "application/vnd.android.package-archive"),
            arrayOf(".asf", "video/x-ms-asf"),
            arrayOf(".avi", "video/x-msvideo"),
            arrayOf(".bin", "application/octet-stream"),
            arrayOf(".bmp", "image/bmp"),
            arrayOf(".c", "text/plain"),
            arrayOf(".class", "application/octet-stream"),
            arrayOf(".conf", "text/plain"),
            arrayOf(".cpp", "text/plain"),
            arrayOf(".doc", "application/msword"),
            arrayOf(".docx", "application/msword"),
            arrayOf(".exe", "application/octet-stream"),
            arrayOf(".gif", "image/gif"),
            arrayOf(".gtar", "application/x-gtar"),
            arrayOf(".gz", "application/x-gzip"),
            arrayOf(".h", "text/plain"),
            arrayOf(".htm", "text/html"),
            arrayOf(".html", "text/html"),
            arrayOf(".jar", "application/java-archive"),
            arrayOf(".java", "text/plain"),
            arrayOf(".jpeg", "image/jpeg"),
            arrayOf(".JPEG", "image/jpeg"),
            arrayOf(".jpg", "image/jpeg"),
            arrayOf(".js", "application/x-javascript"),
            arrayOf(".log", "text/plain"),
            arrayOf(".m3u", "audio/x-mpegurl"),
            arrayOf(".m4a", "audio/mp4a-latm"),
            arrayOf(".m4b", "audio/mp4a-latm"),
            arrayOf(".m4p", "audio/mp4a-latm"),
            arrayOf(".m4u", "video/vnd.mpegurl"),
            arrayOf(".m4v", "video/x-m4v"),
            arrayOf(".mov", "video/quicktime"),
            arrayOf(".mp2", "audio/x-mpeg"),
            arrayOf(".mp3", "audio/x-mpeg"),
            arrayOf(".mp4", "video/mp4"),
            arrayOf(".mpc", "application/vnd.mpohun.certificate"),
            arrayOf(".mpe", "video/mpeg"),
            arrayOf(".mpeg", "video/mpeg"),
            arrayOf(".mpg", "video/mpeg"),
            arrayOf(".mpg4", "video/mp4"),
            arrayOf(".mpga", "audio/mpeg"),
            arrayOf(".msg", "application/vnd.ms-outlook"),
            arrayOf(".ogg", "audio/ogg"),
            arrayOf(".pdf", "application/pdf"),
            arrayOf(".png", "image/png"),
            arrayOf(".pps", "application/vnd.ms-powerpoint"),
            arrayOf(".ppt", "application/vnd.ms-powerpoint"),
            arrayOf(".pptx", "application/vnd.ms-powerpoint"),
            arrayOf(".prop", "text/plain"),
            arrayOf(".rar", "application/x-rar-compressed"),
            arrayOf(".rc", "text/plain"),
            arrayOf(".rmvb", "audio/x-pn-realaudio"),
            arrayOf(".rtf", "application/rtf"),
            arrayOf(".sh", "text/plain"),
            arrayOf(".tar", "application/x-tar"),
            arrayOf(".tgz", "application/x-compressed"),
            arrayOf(".txt", "text/plain"),
            arrayOf(".wav", "audio/x-wav"),
            arrayOf(".wma", "audio/x-ms-wma"),
            arrayOf(".wmv", "audio/x-ms-wmv"),
            arrayOf(".wps", "application/vnd.ms-works"),
            arrayOf(".xml", "text/plain"),
            arrayOf(".z", "application/x-compress"),
            arrayOf(".zip", "application/zip"),
            arrayOf("", "*/*")
        )

    fun stringToAscii(value: String): Int {
        val sbu = StringBuffer()
        val chars = value.toCharArray()
        for (i in chars.indices) {
            if (i != chars.size - 1) {
                sbu.append(chars[i].toInt()).append(",")
            } else {
                sbu.append(chars[i].toInt())
            }
        }
        return sbu.toString().toInt()
    }

    fun byteToHexString(byteArray: ByteArray): String? {
        var str = ""
        if (byteArray.isEmpty()) {
            return null
        }
        byteArray.forEach { it ->
            val v: Int = it.toInt() and 0xFF
            val hx = Integer.toHexString(v)
            if (hx.length < 2) {
                str += "0"
            }
            str += hx
        }
        return str
    }

    // To check if service is enabled
    fun isAccessibilitySettingsOn(mContext: Context): Boolean {
        var accessibilityEnabled = 0
        val service =
            "com.test.package.name/com.test.package.name.YOURAccessibilityService"
        val accessibilityFound = false
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                mContext.applicationContext.contentResolver,
                Settings.Secure.ACCESSIBILITY_ENABLED
            )
        } catch (e: Settings.SettingNotFoundException) {

        }
        val mStringColonSplitter = SimpleStringSplitter(':')
        if (accessibilityEnabled == 1) {
            val settingValue = Settings.Secure.getString(
                mContext.applicationContext.contentResolver,
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
            )
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue)
                while (mStringColonSplitter.hasNext()) {
                    val accessabilityService = mStringColonSplitter.next()
                    if (accessabilityService.equals(service, ignoreCase = true)) {

                        return true
                    }
                }
            }
        }
        return accessibilityFound
    }


    @Throws(RuntimeException::class)
    fun isAccessibilityEnabled(context: Context?): Boolean {
        if (context == null) {
            return false
        }

        // 检查AccessibilityService是否开启
        val am: AccessibilityManager =
            context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
        val isAccessibilityEnabled_flag: Boolean = am.isEnabled
        var isExploreByTouchEnabled_flag = false

        // 检查无障碍服务是否以语音播报的方式开启
        isExploreByTouchEnabled_flag = isScreenReaderActive(context)
        return isAccessibilityEnabled_flag && isExploreByTouchEnabled_flag
    }

    private const val SCREEN_READER_INTENT_ACTION =
        "android.accessibilityservice.AccessibilityService"
    private const val SCREEN_READER_INTENT_CATEGORY =
        "android.accessibilityservice.category.FEEDBACK_SPOKEN"

    private fun isScreenReaderActive(context: Context): Boolean {

        // 通过Intent方式判断是否存在以语音播报方式提供服务的Service，还需要判断开启状态
        val screenReaderIntent = Intent(SCREEN_READER_INTENT_ACTION)
        screenReaderIntent.addCategory(SCREEN_READER_INTENT_CATEGORY)
        val screenReaders: List<ResolveInfo>? =
            context.packageManager.queryIntentServices(screenReaderIntent, 0)
        // 如果没有，返回false
        if (screenReaders == null || screenReaders.isEmpty()) {
            return false
        }
        var hasActiveScreenReader = false
        if (Build.VERSION.SDK_INT <= 15) {
            val cr: ContentResolver = context.contentResolver
            var cursor: Cursor? = null
            var status = 0
            for (screenReader in screenReaders) {
                cursor = cr.query(
                    Uri.parse(
                        "content://" + screenReader.serviceInfo.packageName
                            .toString() + ".providers.StatusProvider"
                    ), null, null, null, null
                )
                if (cursor != null && cursor.moveToFirst()) {
                    status = cursor.getInt(0)
                    cursor.close()
                    // 状态1为开启状态，直接返回true即可
                    if (status == 1) {
                        return true
                    }
                }
            }
        } else if (Build.VERSION.SDK_INT >= 26) {
            // 高版本可以直接判断服务是否处于开启状态
            for (screenReader in screenReaders) {
                hasActiveScreenReader = hasActiveScreenReader or isAccessibilitySettingsOn(
                    context,
                    screenReader.serviceInfo.packageName.toString() + "/" + screenReader.serviceInfo.name
                )
            }
        } else {
            // 判断正在运行的Service里有没有上述存在的Service
            val runningServices: List<String> = ArrayList()
            val manager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            for (service in manager.getRunningServices(Int.MAX_VALUE)) {
                runningServices.plus(service.service.packageName)
            }
            for (screenReader in screenReaders) {
                if (runningServices.contains(screenReader.serviceInfo.packageName)) {
                    hasActiveScreenReader = hasActiveScreenReader or true
                }
            }
        }
        return hasActiveScreenReader
    }

    // To check if service is enabled
    private fun isAccessibilitySettingsOn(
        context: Context,
        service: String
    ): Boolean {
        val mStringColonSplitter = TextUtils.SimpleStringSplitter(':')
        val settingValue = Settings.Secure.getString(
            context.applicationContext.contentResolver,
            Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
        )
        if (settingValue != null) {
            mStringColonSplitter.setString(settingValue)
            while (mStringColonSplitter.hasNext()) {
                val accessibilityService: String = mStringColonSplitter.next()
                if (accessibilityService.equals(service, ignoreCase = true)) {
                    return true
                }
            }
        }
        return false
    }

    fun transparency(context: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            context.window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            context.window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            context.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            context.window.statusBarColor = Color.TRANSPARENT;
        }
    }

    fun reNameExt(old: String, newExt: String): String {
        val oldL = old.split(".")
        val newN = old.replace(oldL[oldL.size - 1], newExt)
        if (newN == newExt) {
            return "$old.$newExt"
        }
        return newN
    }

    fun getPathExtend(name: String): String {
        return name.split(".")[name.split(".").size - 1]
    }

    fun deletes(file: File?) {
        if (file!!.isFile) {
            file.delete()
        }
        if (file.isDirectory) {
            val childFile = file.listFiles()
            if (childFile!!.isEmpty()) {
                file.delete()
            }
            childFile.forEach {
                deletes(it)
            }
        }
        file.delete()
    }

    fun writeSetting(context: Context, key: String, value: String) {
        val setFPath = context.filesDir.path + "/setting1.4.json"
        val jsonO = readSetting(context)
        jsonO[key] = value
        EggIO().writeFile(setFPath, jsonO.toJSONString())
    }

    fun readSetting(context: Context): JSONObject {
        val setFPath = context.filesDir.path + "/setting1.4.json"
        if (!File(setFPath).exists()) {
            EggIO().assetsFileToSdPath(context, "setting1.4.json", setFPath)
        }
        return JSON.parseObject(EggIO().readFile(setFPath))
    }

    fun goWeb(context: Context, link: String) {
        val intent = Intent()
        intent.action = "android.intent.action.VIEW"
        intent.data = Uri.parse(link)
        context.startActivity(intent)
    }

    inline fun <reified T> concat(
        a: Array<T?>,
        b: Array<T?>
    ): Array<T?> {
        val c: Array<T?> = arrayOfNulls(a.size + b.size)
        System.arraycopy(a, 0, c, 0, a.size)
        System.arraycopy(b, 0, c, a.size, b.size)
        return c
    }

    /****************
     *
     * 发起添加群流程。群号：APK山盒官方测试群(714212174) 的 key 为： 1oCNJyhSwyS41UHwrD3WKwMpQ8N5RH3Z
     * 调用 joinQQGroup(1oCNJyhSwyS41UHwrD3WKwMpQ8N5RH3Z) 即可发起手Q客户端申请加群 APK山盒官方测试群(714212174)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
     ******************/
    fun joinQQGroup(context: Context, key: String): Boolean {
        val intent = Intent()
        intent.data =
            Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D$key")
        return try {
            context.startActivity(intent)
            true
        } catch (e: java.lang.Exception) {
            toast(context, "您未下载QQ")
            false
        }
    }


    fun bitmap2uri(c: Context, b: Bitmap): Uri? {
        val path =
            File("${c.cacheDir}${File.separator}${System.currentTimeMillis()}.jpg")
        try {
            val os: OutputStream = FileOutputStream(path)
            b.compress(Bitmap.CompressFormat.PNG, 100, os)
            os.close()
            return Uri.fromFile(path)
        } catch (ignored: Exception) {
            ignored.printStackTrace()
        }
        return null
    }

    fun setTranslucentStatus(context: Activity, on: Boolean) {
        val win = context.window
        val wimPar = win.attributes
        val bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
        if (on) {
            wimPar.flags = bits
        } else {
            wimPar.flags = bits
        }
        win.attributes = wimPar
    }

    fun getBitmapFromDrawable(drawable: Drawable): Bitmap? {
        val bmp = Bitmap.createBitmap(
            drawable.intrinsicWidth,
            drawable.intrinsicHeight,
            Bitmap.Config.ARGB_4444
        )

        bmp.setHasAlpha(true)


        val canvas = Canvas()
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
        canvas.setBitmap(bmp)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        return bmp
    }


    fun <T> setViewIcon(context: Context, view: T, path: String) {
        if (view is ImageView) {
            view.setImageBitmap(BitmapFactory.decodeStream(context.assets.open(path)))
        }
    }


    fun startApp(context: Context, pack: String) {
        val packageManager = context.packageManager;
        val intent = packageManager.getLaunchIntentForPackage(pack)
        context.startActivity(intent)
    }

    /**
     * 开启设置安装未知来源应用权限界面
     *
     * @param context
     */
//@RequiresApi (api = Build.VERSION_CODES.O)
    fun startInstallPermissionSettingActivity(context: Context?) {
        if (context == null) {
            return
        }
        val intent = Intent()
        //获取当前apk包URI，并设置到intent中（这一步设置，可让“未知应用权限设置界面”只显示当前应用的设置项）
        val packageURI =
            Uri.parse("package:" + context.packageName)
        intent.data = packageURI
        //设置不同版本跳转未知应用的动作
        if (Build.VERSION.SDK_INT >= 26) { //intent = new Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
            intent.action = Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES
        } else {
            intent.action = Settings.ACTION_SECURITY_SETTINGS
        }
        //Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        (context as Activity).startActivityForResult(
            intent,
            2
        )
    }




    private fun getMIMEType(file: File): String? {
        var type = "*/*"
        val fName = file.name
        //获取后缀名前的分隔符"."在fName中的位置。
        val dotIndex = fName.lastIndexOf(".")
        if (dotIndex < 0) return type
        /* 获取文件的后缀名 */
        val fileType = fName.substring(dotIndex, fName.length).toLowerCase()
        if ("" == fileType) return type
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (i in MIME_MapTable.indices) {
            if (fileType == MIME_MapTable[i][0]) type = MIME_MapTable[i][1]
        }
        return type
    }

    fun openAndroidFile(context: Context,filepath: String?) {
        val intent = Intent()
        val file = File(filepath!!)
        //        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//设置标记
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.action = Intent.ACTION_VIEW //动作，查看
        intent.setDataAndType(Uri.fromFile(file), getMIMEType(file)) //设置类型
        context.startActivity(intent)
    }

    fun startInstall(context: Context, fileName: String) {
        val newFile = File(File(context.filesDir, "apk"), fileName)
        newFile.parentFile?.let {
            if (!it.exists()) {
                it.mkdirs()
            }
        }

        val apkUri = FileProvider.getUriForFile(
            context,
            "com.srcbox.file",
            newFile
        )
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        context.startActivity(intent)
    }


    fun checkDirExist(file: File): Boolean {
        return if (!file.exists()) {
            file.mkdirs()
        } else {
            true
        }
    }

    /**
     * 通知android媒体库更新文件夹
     *
     * @param filePath ilePath 文件绝对路径，、/sda/aaa/jjj.jpg
     */
    fun scanFile(context: Context, filePath: String) {
        MediaScannerConnection.scanFile(
            context,
            arrayOf(filePath),
            null,
            MediaScannerConnection.OnScanCompletedListener { path, uri ->
                println("$path$uri")
            })
    }

    fun saveFile(input: InputStream, file: File) {
        checkDirExist(file.parentFile!!)
        val fos = FileOutputStream(file)
        var len = 0
        val buffer = ByteArray(524)
        while (input.read(buffer).apply { len = this } != -1) {
            fos.write(buffer, 0, len)
        }
        fos.flush()
        fos.close()
        input.close()
    }

    fun saveBitmap(bit: Bitmap?, file: File) {
        checkDirExist(file.parentFile!!)
        val fos = FileOutputStream(file)
        bit?.compress(Bitmap.CompressFormat.PNG, 100, fos)
        fos.flush()
        fos.close()
    }

    fun saveDrawable(
        draw: Drawable?,
        file: File,
        context: Context? = null, isUpdate: Boolean = false
    ) {
        checkDirExist(file.parentFile!!)
        val bit = (draw as BitmapDrawable).bitmap
        val fos = FileOutputStream(file)
        bit.compress(Bitmap.CompressFormat.PNG, 100, fos)
        fos.flush()
        fos.close()
        if (isUpdate) {
            scanFile(context!!, file.path)
        }
    }

    fun shareFile(activity: Activity, fileUrl: String, fileName: String) {
        val newFile = File(File(activity.filesDir, "apk"), "$fileName.apk")
        newFile.parentFile?.let {
            if (!it.exists()) {
                it.mkdirs()
            }
        }

        EggIO().copyFileTo(
            FileInputStream(fileUrl),
            FileOutputStream(newFile)
        )

        val shareIntent = Intent(Intent.ACTION_SEND)
        shareIntent.putExtra(
            Intent.EXTRA_STREAM,
            FileProvider.getUriForFile(
                activity,
                "com.srcbox.file",
                newFile
            )
        )
        shareIntent.type = "*/*"
        activity.startActivity(Intent.createChooser(shareIntent, "分享到："))
    }

    fun setSwitchColor(v: SwitchCompat) {
        // thumb color
        val thumbColor = AppSetting.STRESS__TRANS_COLOR
        // trackColor
        val trackColor = AppSetting.STRESS__TRANS_COLOR
        // set the thumb color
        DrawableCompat.setTintList(
            v.thumbDrawable, ColorStateList(
                arrayOf(intArrayOf(R.attr.state_checked), intArrayOf()),
                intArrayOf(
                    Color.parseColor(trackColor),
                    Color.parseColor(thumbColor)
                )
            )
        )
        // set the track color
        DrawableCompat.setTintList(
            v.trackDrawable, ColorStateList(
                arrayOf(intArrayOf(R.attr.state_checked), intArrayOf()),
                intArrayOf(
                    0x4DFF6633,
                    0x4d2f2f2f
                )
            )
        )
    }

    fun hideKeyboard(activity: Activity) {
        val inputMethodsMan =
            activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodsMan.hideSoftInputFromWindow(activity.window.decorView.applicationWindowToken, 0)
    }

    fun statusBarLightMode(activity: Activity): Int {
        var result = 0
        when {
            MIUISetStatusBarLightMode(activity.window, true) -> {
                result = 1
            }
            FlymeSetStatusBarLightMode(activity.window, true) -> {
                result = 2
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
                activity.window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                result = 3
            }
        }
        return result
    }


    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     * @param window 需要设置的窗口
     * @param dark 是否把状态栏字体及图标颜色设置为深色
     * @return  boolean 成功执行返回true
     */
    fun FlymeSetStatusBarLightMode(window: Window?, dark: Boolean): Boolean {
        var result = false
        if (window != null) {
            try {
                val lp: WindowManager.LayoutParams = window.getAttributes()
                val darkFlag: Field = WindowManager.LayoutParams::class.java
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
                val meizuFlags: Field = WindowManager.LayoutParams::class.java
                    .getDeclaredField("meizuFlags")
                darkFlag.isAccessible = true
                meizuFlags.isAccessible = true
                val bit: Int = darkFlag.getInt(null)
                var value: Int = meizuFlags.getInt(lp)
                value = if (dark) {
                    value or bit
                } else {
                    value and bit.inv()
                }
                meizuFlags.setInt(lp, value)
                window.attributes = lp
                result = true
            } catch (e: java.lang.Exception) {
            }
        }
        return result
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     * @param window 需要设置的窗口
     * @param dark 是否把状态栏字体及图标颜色设置为深色
     * @return  boolean 成功执行返回true
     */
    private fun MIUISetStatusBarLightMode(window: Window?, dark: Boolean): Boolean {
        var result = false
        if (window != null) {
            val clazz: Class<*> = window.javaClass
            try {
                var darkModeFlag = 0
                val layoutParams =
                    Class.forName("android.view.MiuiWindowManager\$LayoutParams")
                val field: Field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
                darkModeFlag = field.getInt(layoutParams)
                val extraFlagField: Method = clazz.getMethod(
                    "setExtraFlags",
                    Int::class.javaPrimitiveType,
                    Int::class.javaPrimitiveType
                )
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag) //状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag) //清除黑色字体
                }
                result = true
            } catch (e: java.lang.Exception) {
            }
        }
        return result
    }


    fun setTypeface(activity: Activity, textView: TextView) {
        val typeface = Typeface.createFromAsset(activity.assets, "fonts/t.ttf")
        textView.typeface = typeface
    }

    fun goQQ(activity: Activity, qqNum: String) {
        activity.startActivity(
            Intent(
                Intent.ACTION_VIEW,
                Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=$qqNum&version=1")
            )
        )
    }

    fun loadIcon(activity: Activity, textView: TextView, color: String = AppSetting.STRESS_COLOR) {
        textView.typeface = Typeface.createFromAsset(activity.assets, "iconfont.ttf")
        textView.setTextColor(Color.parseColor(color))
    }

    fun copyText(activity: Activity, string: String) {
        val clip = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val clipData = ClipData.newPlainText("label", string)
        clip.setPrimaryClip(clipData)
    }

    /**
     *设置控件圆角
     */

    fun setViewRadius(view: View, color: String, width: Int, sideColor: String, radius: Float) {
        val gradientDrawable = GradientDrawable()
        gradientDrawable.setColor(Color.parseColor(color))
        gradientDrawable.setStroke(width, Color.parseColor(sideColor))
        gradientDrawable.cornerRadius = radius
        view.background = gradientDrawable
    }

    fun setViewRadii(view: View, color: String, width: Int, sideColor: String, radius: FloatArray) {
        val gradientDrawable = GradientDrawable()
        gradientDrawable.setColor(Color.parseColor(color))
        gradientDrawable.setStroke(width, Color.parseColor(sideColor))
//        gradientDrawable.cornerRadius = radius
        gradientDrawable.cornerRadii = radius
        view.background = gradientDrawable
    }

    /**
     * convert px to its equivalent dp
     *
     * 将px转换为与之相等的dp
     */
    fun px2dp(context: Context, pxValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }


    /**
     * convert dp to its equivalent px
     *
     * 将dp转换为与之相等的px
     */
    fun dp2px(context: Context, dipValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dipValue * scale + 0.5f).toInt()
    }


    /**
     * convert px to its equivalent sp
     *
     * 将px转换为sp
     */
    fun px2sp(context: Context, pxValue: Float): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (pxValue / fontScale + 0.5f).toInt()
    }


    /**
     * convert sp to its equivalent px
     *
     * 将sp转换为px
     */
    fun sp2px(context: Context, spValue: Float): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (spValue * fontScale + 0.5f).toInt()
    }

    fun alterStateBarColor(activity: Activity, color: String) {
        activity.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        activity.window.statusBarColor = Color.parseColor(color)
//        ContextCompat.getColor(activity, Color.parseColor("#5555"))
    }

    fun toast(context: Context, string: String, isLong: Boolean = false) {
        var length = Toast.LENGTH_SHORT
        if (isLong) {
            length = Toast.LENGTH_LONG
        }
        Toast.makeText(context, string, length).show()
    }

    fun getStatusBarHeight(context: Context): Int {
        val resources: Resources = context.resources
        val resourceId: Int = resources.getIdentifier("status_bar_height", "dimen", "android")
        return resources.getDimensionPixelSize(resourceId)
    }

    fun getPhoneDisplay(context: Context): Point {
        val winManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val point = Point()
        winManager.defaultDisplay.getRealSize(point)
        return point
    }

    fun cutBitmap(bit: Bitmap?, x: Int, y: Int, w: Int, h: Int): Bitmap? {
        return try {
            Bitmap.createBitmap(bit!!, x, y, w, h)
        } catch (e: Exception) {
            println(e.message)
            null
        }
    }

    fun saveBitmapFile(bitmap: Bitmap?, path: String) {
        val bos = BufferedOutputStream(FileOutputStream(File(path)))
        bitmap?.compress(Bitmap.CompressFormat.PNG, 100, bos)
        bos.flush()
        bos.close()
    }

    fun inputStream2Bitmap(inputStream: InputStream): Bitmap {
        val buff = ByteArray(524)
        var len = 0
        val byteOutStream = ByteArrayOutputStream()
        while ((inputStream.read(buff).apply { len = this }) != -1) {
            byteOutStream.write(buff, 0, len)
        }
        val byteArr = byteOutStream.toByteArray()
        byteOutStream.close()
        inputStream.close()
        return BitmapFactory.decodeByteArray(byteArr, 0, byteArr.size)
    }
}